package term

import (
	"context"
	// "fmt"
	"strings"
	"time"

	"mall/service/attachment/model"
	"mall/service/attachment/rpc/internal/svc"
	"mall/service/attachment/rpc/internal/utils"
	"mall/service/attachment/rpc/internal/utils/errorhandler"
	"mall/service/attachment/rpc/types/attachment"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"

	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateTermLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateTermLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateTermLogic {
	return &BackendUpdateTermLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendUpdateTermLogic) BackendUpdateTerm(in *attachment.TermInfo) (*attachment.BaseResp, error) {
	if len(in.Ids) > 0 {
		tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				term, err := l.svcCtx.MediaTerm.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				if in.Status != nil {
					term.Status = uint8(*in.Status)
				}
				term.UpdatedAt = now
				err = l.svcCtx.MediaTerm.Update(l.ctx, tx, term, nil)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &attachment.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	id := *in.Id
	term, err := l.svcCtx.MediaTerm.FindOneNoCache(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Taxonomy != nil {
		taxonomy := utils.ParseTaxonomy(strings.TrimSpace(*in.Taxonomy))
		if taxonomy > 0 {
			term.Taxonomy = uint16(taxonomy)
		}
	}
	if in.Name != nil {
		term.Name = strings.TrimSpace(*in.Name)

		if len(term.Name) == 0 {
			return nil, errorx.NewInvalidArgumentError("term.nameRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttachmentTermColumns.Name] = map[string][]any{
			"equalTo": []any{term.Name},
		}
		filterMap[model.AttachmentTermColumns.Taxonomy] = map[string][]any{
			"equalTo": []any{term.Taxonomy},
		}
		list, _, err := l.svcCtx.MediaTerm.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("term.nameAlreadyExists")
		}

		if count == 1 && list[0].TermID != id {
			return nil, errorx.NewAlreadyExistsError("term.nameAlreadyExists")
		}
	}
	if in.Slug != nil {
		term.Slug = strings.TrimSpace(*in.Slug)
	}
	if in.ParentId != nil {
		term.ParentID = *in.ParentId
	}
	if in.GroupId != nil {
		term.TermGroup = uint16(*in.GroupId)
	}
	if in.Desc != nil {
		term.Description = strings.TrimSpace(*in.Desc)
	}
	if in.FilteredDesc != nil {
		term.DescriptionFiltered = strings.TrimSpace(*in.FilteredDesc)
	}
	if in.Sort != nil {
		term.Sort = uint16(*in.Sort)
	}
	if in.Status != nil {
		term.Status = uint8(*in.Status)
	}
	term.UpdatedAt = time.Now()
	rel := &model.AttachmentTermRel{}
	if len(in.Meta) > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttachmentTermMetumColumns.TermID] = map[string][]any{
			"equalTo": []any{id},
		}
		list, _, err := l.svcCtx.MediaTerm.GetMeta(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 { // 原有的 Meta（决定现有的是增还是改）
			var mids []uint64
			omidMap := make(map[uint64]struct{})
			for _, v := range list {
				mids = append(mids, v.MetaID)
				omidMap[v.MetaID] = struct{}{}
			}

			// 现有的 Meta（决定原有的是删还是留）
			nmidMap := make(map[uint64]struct{})
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.AttachmentTermMetum
				metum.TermID = id
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

				if v.Id != nil && *v.Id > 0 {
					if _, ok := omidMap[*v.Id]; ok { // 有值且是有效值
						nmidMap[*v.Id] = struct{}{}
						metum.MetaID = *v.Id
					}
				}

				rel.Meta = append(rel.Meta, &metum)
			}

			for _, mid := range mids {
				if _, ok := nmidMap[mid]; !ok { // 当前不存在的值
					rel.DelMetumIds = append(rel.DelMetumIds, mid)
				}
			}
		} else {
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.AttachmentTermMetum
				metum.TermID = id
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))
				rel.Meta = append(rel.Meta, &metum)
			}
		}
	}
	// logrus.Info(fmt.Sprintf("BackendUpdateTerm rel: %+v", rel))
	err = l.svcCtx.MediaTerm.Update(l.ctx, nil, term, rel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &attachment.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
